﻿using BepInEx;
using CasselGames.Input;
using HarmonyLib;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using MEC;
using Newtonsoft.Json;
namespace BetterBlackTrading {
    [BepInPlugin("betterBlackTrading", "BetterBlackTrading", "1.0.0")]
    public class Plugin: BaseUnityPlugin {

        private static bool isInit;
        private const int BLACK_TRADER_INDEX = 5; // 黑色交易站商人索引

        private void Awake() {
            Harmony.CreateAndPatchAll(typeof(Plugin));
            Logger.LogInfo("BetterBlackTrading mod initialized!");
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(DB_Mgr), "Awake")]
        public static void DB_Mgr_Awake_Prefix(DB_Mgr __instance) {
            if (!isInit) {
                isInit = true;
                LoadAndApplyBlackTraderConfig(__instance);
              
            }
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(DB_Mgr), "Awake")]
        public static void DB_Mgr_Awake_Postfix(DB_Mgr __instance) {
            //Debug.Log(JsonConvert.SerializeObject(GameMgr.Instance._DB_Mgr.m_QueenAbilityDB._list));
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Building_TradingPost), "Building_Update2")]
        public static bool Building_TradingPost_Building_Update2_Prefix(Building_TradingPost __instance, float _dir = 0f) {
            if (__instance.m_Info.Name == BuildingName.BlackTradingPost) {
                if (__instance.m_ProductIndex != (int)GameMgr.Instance._WeatherMgr.m_SeasonState) {
                    if (__instance.m_Body.m_Animator != null) {
                        __instance.m_Body.m_Animator.Play("Action");
                    }
                    __instance.m_ProductIndex = (int)GameMgr.Instance._WeatherMgr.m_SeasonState;

                    //重写刷新黑市方法
                    TradeNPC tradeNPC = GameMgr.Instance._DB_Mgr.m_TradingNPCDB._list[5];
                    GameMgr.Instance._SysMgr.List_BoneSellType.Clear();
                    GameMgr.Instance._SysMgr.List_BoneSellNum.Clear();
                    var extendSellList = new List<TileType>();
                    var newSellDic = new Dictionary<TileType,int>();
                    for (int i = 0; i < tradeNPC.List_Sell.Count; i++) {
                        if (i >= 8) {
                            extendSellList.Add(tradeNPC.List_Sell[i]);
                        } else {
                            newSellDic.Add(tradeNPC.List_Sell[i], tradeNPC.List_Sell_Num[i]);
                        }
                    }
                    var randomSellList = GetRandomElementsWithoutReplacement(extendSellList, 2);
                    for(int i = 0; i < tradeNPC.List_Sell.Count; i++) {
                        for(int j=0; j < randomSellList.Count; j++) {
                            if (tradeNPC.List_Sell[i] == randomSellList[j]) {
                                newSellDic.Add(randomSellList[j], tradeNPC.List_Sell_Num[i]);
                            }
                        }
                    }
                    GameMgr.Instance._SysMgr.List_BoneSellType = new List<TileType>(newSellDic.Keys);
                    float num = GameMgr.Instance._DB_Mgr.GetBuildInfo(__instance.m_Info.Name).EffectValue1_Num * 0.1f;
                    for (int i = 0; i < tradeNPC.List_Sell_Num.Count; i++) {
                        if (newSellDic.ContainsKey(tradeNPC.List_Sell[i])) {
                            GameMgr.Instance._SysMgr.List_BoneSellNum.Add((int)((float)newSellDic[tradeNPC.List_Sell[i]] * num));
                        }
                    }

                    __instance.List_PlantInfo = new List<TileType>(GameMgr.Instance._SysMgr.List_BoneSellType);
                    //TODO：调用私有方法                    
                    var SkinChangeC = (IEnumerator<float>)Traverse.Create(__instance).Method("SkinChangeC", "Basic/" + tradeNPC.SkinName, tradeNPC.Index, GameMgr.Instance._SysMgr.List_BoneSellType, (int)_dir).GetValue();
                    Timing.RunCoroutine(SkinChangeC);
                    return false;
                }
               
            }
            return true;
        }


        private static void LoadAndApplyBlackTraderConfig(DB_Mgr dbMgr) {
            string configPath = Path.Combine(Paths.ConfigPath, "BetterBlackTradingConfig.csv");
            Debug.Log($"LoadAndApplyBlackTraderConfig：{configPath}");
            if (!File.Exists(configPath)) {
                Debug.LogError($"[BetterBlackTrading] Config file not found at: {configPath}");
                return;
            }

            try {
                var trader = dbMgr.m_TradingNPCDB._list[BLACK_TRADER_INDEX];
                var newSellList = new List<TileType>();
                var newSellNumList = new List<int>();

                var lines = File.ReadAllLines(configPath);

                // 跳过标题行
                foreach (var line in lines.Skip(1)) {
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    var parts = line.Split('\t');
                    if (parts.Length < 2)
                        continue;

                    // 解析物品类型
                    if (Enum.TryParse(parts[0].Trim(), out TileType itemType)) {
                        // 解析数量
                        if (int.TryParse(parts[1].Trim(), out int quantity)) {
                            newSellList.Add(itemType);
                            newSellNumList.Add(quantity);
                        }
                    }
                }
                if (newSellList.Count == 0) {
                    Debug.Log("[BetterBlackTrading] No valid items found in config. Using default setup.");
                    return;
                }
                // 应用新配置
                trader.List_Sell.AddRange(newSellList);
                trader.List_Sell_Num.AddRange(newSellNumList);

                Debug.Log($"[BetterBlackTrading] Successfully loaded {newSellList.Count} items from config");
            } catch (Exception ex) {
                Debug.LogError($"[BetterBlackTrading] Error loading config: {ex.Message}");
            }
        }

        private static List<T> GetRandomElementsWithoutReplacement<T>(List<T> list, int count) {
            if (count > list.Count)
                throw new ArgumentException("count cannot be greater than list size");

            List<T> result = new List<T>();
            List<T> tempList = new List<T>(list); // 避免修改原列表
            System.Random random = new System.Random();

            for (int i = 0; i < count; i++) {
                int index = random.Next(0, tempList.Count);
                result.Add(tempList[index]);
                tempList.RemoveAt(index); // 移除已选元素
            }

            return result;
        }
    }
}
